import { User } from '../models/user';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import {ReplaySubject} from 'rxjs';

@Injectable()
export class UserService {
    private current: ReplaySubject<User> = new ReplaySubject<User>( 1 );
    // Called when logout
    public logoutAction: Function;

    constructor(
      private router: Router
    ) {}

    public setCurrent( user: User ) {
      this.current.next( user );
      localStorage.setItem('user', JSON.stringify(user));
    }

    public getCurrent() {
      // if(! this.current) {
      //
      //   this.current.next( user1 );
      // }
      // return this.current;
      const obj = JSON.parse(localStorage.getItem('user'));
      if(obj){
        const user1 = new User( {
          avatarUrl: obj['avatarUrl'],
          email: obj['email'],
          username: obj['username'],
          connected: true,
        });
        this.current.next( user1 );
      }
      return this.current;
    }

    public logout() {
      if ( this.logoutAction ) {
        this.logoutAction();
      } else {
        const user = new User();
        user.connected = false;
        this.setCurrent( user );
        localStorage.clear();
        this.router.navigate(['/login']);
      }
    }
}
